package com.springcloud.market.api.service.impl;

import com.springcloud.market.api.entity.Stock;
import com.springcloud.market.api.mapper.StockMapper;
import com.springcloud.market.api.service.StockService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@DubboService
public class StockServiceImpl implements StockService {
    
    @Autowired
    private StockMapper stockMapper;
    
    @Override
    public String getStockInfo(){
        return "当前库存服务正常运行";
    }
    
    @Override
    public String reduceStock(Long productId, Integer quantity) {
        // 查询库存（根据商品ID查询，因为id字段就是商品ID）
        Stock stock = stockMapper.selectById(productId);
        
        if (stock == null) {
            return "商品不存在";
        }
        
        // 检查库存是否充足
        if (stock.getCount() < quantity) {
            return "库存不足";
        }
        
        // 扣减库存
        stock.setCount(stock.getCount() - quantity);
        stockMapper.updateById(stock);
        
        return "扣减成功";
    }

    @Override
    public void reduce(Integer productId) {
        Stock stock = stockMapper.selectById(productId);
        stock.setCount(stock.getCount()-1);
        stockMapper.updateById(stock);
    }

}
